package at.fhooe.mc.duel_game;

import at.fhooe.mc.duel_game.bluetooth.BluetoothCommand;



public class DuelCommand implements BluetoothCommand {
	
	// Members
	private Commands cmd;
	private int length;
	private byte[] data;
	
	public DuelCommand(Commands cmd, String data) {
		this.cmd = cmd;
		this.data = data.getBytes();
		this.length = this.data.length;
	}
	
	public DuelCommand(Commands cmd, byte[] data) {
		this.cmd = cmd;
		this.length = data.length;
		this.data = data;
	}
	
	public DuelCommand(Commands cmd, int val) {
		this(cmd, ByteConverters.makeByte4FromInt(val));
	}
	
	public DuelCommand(Commands cmd, long val) {
		this(cmd, ByteConverters.makeByte8FromLong(val));
	}
	
	public DuelCommand(Commands cmd) {
		this.cmd = cmd;
		this.length = 0;
		this.data = new byte[0];
	}	
	
	public Commands getCommand() {
		return this.cmd;
	}
	
	public byte[] GetData() {
		return this.data;
	}
	
	public String GetStrData() {
		return new String(this.data);
	}

	public byte[] getSendData() {
		
		byte[] tempData = new byte[4 + 4  + length];
		
		// src, pos src, dst, pos dst, length
		System.arraycopy(ByteConverters.makeByte4FromInt(cmd.ordinal()), 0, tempData, 0, 4);
		System.arraycopy(ByteConverters.makeByte4FromInt(length), 0, tempData, 4, 4);
		
		if(length > 0)
			System.arraycopy(data, 0,tempData, 8, length);
		
		return tempData;
	}
	
	public static DuelCommand parseData(byte[] data) {
		if(data.length >= 8) {
			byte[] temp = new byte[4]; 
					
			// get cmd enumeration
			System.arraycopy(data, 0, temp, 0, 4);
			Commands cmd = Commands.values()[ByteConverters.makeIntFromByte4(data)];
		
			// get length information
			System.arraycopy(data, 4, temp, 0, 4);
			int length = ByteConverters.makeIntFromByte4(temp);
			
			//get data
			if(length > 0) {
				byte[] tempData = new byte[length];
				System.arraycopy(data, 8, tempData, 0, length);
				return new DuelCommand(cmd, tempData);
			}
			else {
				return new DuelCommand(cmd);
			}
		} else
			return new DuelCommand(Commands.INVALID_CMD);
	}
}
